import { action, observable } from "mobx";
import getWeb3 from '../getWeb3';
import Web3 from 'web3';
class Web3Store {
  @observable web3 = {};
  @observable defaultAccount = '';
  getWeb3Promise = null;
  @observable loading = true;
  @observable errors = [];
  @observable userTokens = [];
  @observable explorerUrl = '';
  @observable contractAddress = '';
  @observable startedUrl = window.location.hash
  constructor(rootStore) {
    
    this.getWeb3Promise = getWeb3().then(async (web3Config) => {
      const {web3Instance, defaultAccount} = web3Config;
      this.defaultAccount = defaultAccount;
      this.web3 = new Web3(web3Instance.currentProvider); 
      this.getUserTokens(web3Config)
      this.setExplorerUrl(web3Config.explorerUrl)
      this.setContractAddress(web3Config.contractAddress)
      console.log('web3 loaded')
    }).catch((e) => {
      console.error(e,'web3 not loaded')
      this.errors.push(e.message)
    })
  }
  @action
  setExplorerUrl(url){
    this.explorerUrl = url
  }
  @action
  setContractAddress(address) {
    this.contractAddress = address;
  }
  @action
  setStartedUrl(url){
    this.startedUrl = url;
  }
  async getUserTokens({trustApiName, defaultAccount}) {
    let url = `https://${trustApiName}.trustwalletapp.com/tokens?address=${defaultAccount}`;
    url = `https://api.blockchair.com/ethereum/dashboards/address/${defaultAccount}?erc_20=true`
    window.fetch(url).then((res) => {
      return res.json()
    }).then((res) => {
      console.log(res)
      console.log(defaultAccount)
      console.log(typeof(defaultAccount))
      console.log(res.data[defaultAccount])
      // let tokens = res.data['0x6b15fa480cd909791be40f9e4993989e8637e483'].layer_2.erc_20.map((contract) => {
      //   let address = contract.token_address;
      //   let symbol = contract.token_symbol;
      //   return {value: address, label: `${symbol} - ${address}`}
      // })
      let tokens = []
      tokens.unshift({
        value: '0x000000000000000000000000000000000000bEEF',
        label: "ETH - Ethereum Native Currency"
      })
      this.userTokens = tokens;
      this.loading = false;
    }).catch((e) => {
      this.loading = false;
      console.error(e);
    })
  }

}

export default Web3Store;